﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Infrastructure.Model.DI;
using Microsoft.Extensions.Logging;
using Model.CommonModel.PageModel;
using Model.EntityModel.Auth;
using Model.EntityModel.SysModel;
using Model.QueryModel.system;
using Repository.IRepository.ISysRepository;
using Repository.Repository.SysRepository;
using Service.IService.ISysService;

namespace Service.Service.SysService
{
    [AppService(ServiceType = typeof(IGroupService), ServiceLifetime = LifeTime.Scoped)]
    public class GroupService : IGroupService
    {
        private readonly IGroupRepository _groupRepo;
        private readonly IUserGroupRepository _userGroupRepo;
        private readonly ILogger<GroupService> _logger;

        public GroupService(
            IGroupRepository groupRepo,
            IUserGroupRepository userGroupRepo,
            ILogger<GroupService> logger)
        {
            _groupRepo = groupRepo;
            _userGroupRepo = userGroupRepo;
            _logger = logger;
        }

        public List<Group> GetActiveGroups()
        {
            try
            {
                return _groupRepo.GetActiveGroups();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取有效组别失败");
                throw;
            }
        }

        public Group GetGroupById(string groupId)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(groupId))
                    throw new ArgumentException("组别ID不能为空", nameof(groupId));

                return _groupRepo.GetGroupById(groupId);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"获取组别信息失败，组别ID: {groupId}");
                throw;
            }
        }

        public bool CreateGroup(Group group)
        {
            try
            {
                if (group == null)
                    throw new ArgumentNullException(nameof(group), "组别信息不能为空");

                // 检查组名是否重复
                var existingGroup = _groupRepo.GetActiveGroups()
                    .FirstOrDefault(g => g.Name == group.Name);

                if (existingGroup != null)
                    throw new InvalidOperationException("组别名称已存在");

                return _groupRepo.CreateGroup(group);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"创建组别失败，组名: {group.Name}");
                throw;
            }
        }

        public bool UpdateGroup(Group group)
        {
            try
            {
                if (group == null)
                    throw new ArgumentNullException(nameof(group), "组别信息不能为空");

                if (!_groupRepo.GroupExists(group.Id))
                    throw new InvalidOperationException("组别不存在");

                // 检查组名是否重复（排除自身）
                var existingGroup = _groupRepo.GetActiveGroups()
                    .FirstOrDefault(g => g.Name == group.Name && g.Id != group.Id);

                if (existingGroup != null)
                    throw new InvalidOperationException("组别名称已存在");

                return _groupRepo.UpdateGroup(group);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"更新组别失败，组别ID: {group.Id}");
                throw;
            }
        }

        public bool UpdateGroupStatus(string groupId, string isActive)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(groupId))
                    throw new ArgumentException("组别ID不能为空", nameof(groupId));

                if (isActive != "Y" && isActive != "N")
                    throw new ArgumentException("状态值必须是Y(有效)或N(无效)", nameof(isActive));

                return _groupRepo.UpdateGroupStatus(groupId, isActive);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"更新组别状态失败，组别ID: {groupId}");
                throw;
            }
        }


        public bool AddUsersToGroup(string groupId, List<string> userIds)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(groupId))
                    throw new ArgumentException("组别ID不能为空", nameof(groupId));

                if (userIds == null || !userIds.Any())
                    throw new ArgumentException("至少需要选择一个用户", nameof(userIds));

                // 验证组别存在性
                if (!_groupRepo.GroupExists(groupId))
                    throw new InvalidOperationException("指定的组别不存在");

                // 添加关联
                return _userGroupRepo.AddUsersToGroupBulk(userIds, groupId);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"添加用户到组别失败，组别ID: {groupId}");
                throw;
            }
        }

        public bool RemoveUsersFromGroup(string groupId, List<string> userIds)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(groupId))
                    throw new ArgumentException("组别ID不能为空", nameof(groupId));

                if (userIds == null || !userIds.Any())
                    throw new ArgumentException("至少需要选择一个用户", nameof(userIds));

                return _userGroupRepo.RemoveUsersFromGroupBulk(userIds, groupId);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"从组别移除用户失败，组别ID: {groupId}");
                throw;
            }
        }

        public List<User> GetGroupUsers(string groupId)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(groupId))
                    throw new ArgumentException("组别ID不能为空", nameof(groupId));

                var relations = _userGroupRepo.GetUserGroups(groupId);
                var userIds = relations.Select(r => r.UserId).ToList();

                if (!userIds.Any())
                    return new List<User>();

                // 注意：这里需要实现根据ID列表获取用户的方法
                // 实际项目中需要添加此方法到IUserMasterRepository
                // return _userRepo.GetUsersByIds(userIds);
                throw new NotImplementedException("根据ID列表获取用户的方法尚未实现");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"获取组别用户失败，组别ID: {groupId}");
                throw;
            }
        }

        public List<Group> GetGroupsByIds(List<string> ids)
        {
            return _groupRepo.GetGroupsByIds(ids);
        }

        public bool GroupExists(string groupId)
        {
            return _groupRepo.GroupExists(groupId);
        }

        public PagedInfo<Group> GetPageGroup(int pageNum, int pageSize, QueryGroup search)
        {
           return _groupRepo.GetPageGroup(pageNum, pageSize, search);
        }
    }
}
